//
//  AuditMenuViewController.m
//  auditorias
//
//  Created by Mauro on 7/30/13.
//  Copyright (c) 2013 Antilope. All rights reserved.
//

#import "AuditMenuViewController.h"
#import "SharedMemory.h"
#import "ControlVariables.h"
#import "PointOfSell.h"
#import "User.h"
#import "AuditType.h"
#import "AuditQuestionViewController.h"

@interface AuditMenuViewController ()

@end

@implementation AuditMenuViewController

@synthesize items;
@synthesize table;
@synthesize currentSelection;
@synthesize pointOfSell;

static int pointOfSellIndexOld = -1;

- (void) dealloc
{
    [items release], items = nil ;
    [table release], table = nil;
    [pointOfSell release], pointOfSell = nil;
    [_topBarView release];
    [super dealloc];
}

- (void)viewDidUnload
{
    self.items = nil;
    self.table = nil;
    self.pointOfSell = nil;
    [super viewDidUnload];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [TopBarViewController setTitleLabelOf:_topBarView text:kTopBarTitleAuditMenu];
    
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    SharedMemory *mem = [SharedMemory sharedInstance];
    self.currentSelection = mem.auditTypeIndex;
    self.pointOfSell = [mem getPointOfSell];
    
    //IF the PDV was changed, the marked AuditTypes should be erased
    if(pointOfSellIndexOld!=mem.pointOfSellIndex){
        pointOfSellIndexOld=mem.pointOfSellIndex;
        [mem resetAuditTypesDone];
    }
    
    UILabel *titleLabel = (UILabel *)[self.view viewWithTag:30];
    [titleLabel setText:self.pointOfSell.name];
    
    self.items = [[[NSMutableArray alloc] initWithArray:mem.auditTypes] autorelease];  
    
    [self loadTable];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView: (UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger)section
{
    return [items count];
}

- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AuditMenuCell"];
    AuditType* a = [self.items objectAtIndex:[indexPath row] ];
    
    UILabel *descriptionLabel = (UILabel *)[cell viewWithTag:11];
    [descriptionLabel setText:a.name];
    UIView *selectionColor = [[[UIView alloc] init] autorelease];
    UIView *bgColor = [[[UIView alloc] init] autorelease];
    
    selectionColor.backgroundColor =  bgColor.backgroundColor= [self isOnItemsDoneList:a] ? [UIColor colorWithRed:(221/255.0) green:(221/255.0) blue:(221/255.0) alpha:1] : [UIColor clearColor];
    
    cell.backgroundView = bgColor;
    cell.selectedBackgroundView = selectionColor;
    
    return cell;
}

//If its marked, then it returns true.
- (bool) isOnItemsDoneList:(AuditType*) a
{
    SharedMemory *mem = [SharedMemory sharedInstance];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary* dic = [defaults dictionaryForKey:ONEMONTH_AUDITS_KEY];
    if (dic==nil)
        return false;
    NSString* key = [mem makePDVnTypeId:self.pointOfSell auditType:a];
    NSString* dateString = [dic objectForKey:key];
    if (dateString!=nil) {
        if(![mem isOlderThanAMonth:dateString]){
            return true;
        }
        [mem forgetKeyOn:ONEMONTH_AUDITS_KEY key:key];
    }
    return false;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.currentSelection = [indexPath row];
    SharedMemory *mem = [SharedMemory sharedInstance];
    mem.auditTypeIndex = self.currentSelection;
}

- (IBAction)finishButtonTapped:(id)sender
{
    SharedMemory *mem = [SharedMemory sharedInstance];
    if(mem.auditTypeIndex==-1 || [items count]<=mem.auditTypeIndex){
        [SharedMemory showError:@"" andText:auditmenu_must_select];
        return;
    }
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary* dic = [defaults dictionaryForKey:UNSYNC_AUDITS_KEY];
    if (dic!=nil && [dic objectForKey:[mem makeOwnPDVnTypeId]]!=nil ) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:auditmenu_unsync_audit_confirm delegate:self  cancelButtonTitle:@"No" otherButtonTitles:@"Si",nil];
        [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:NO];
        [alert release];
        return;
    }
    [self performSegueWithIdentifier:@"ToQuestion" sender:self];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"ToQuestion"]) {
        //Sets the uniqueID for the next view
        AuditQuestionViewController* vc = [segue destinationViewController];
        vc.uniqueId = [NSString stringWithFormat:@"%.0f",([[NSDate date] timeIntervalSince1970]*1000) ];
    }
}

- (void) loadTable
{
    [self.table reloadData];
    //To start with a marked one
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.currentSelection inSection:0];
    [self.table selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
    [self.table.delegate tableView:self.table didSelectRowAtIndexPath:indexPath];
}

-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ([[alertView buttonTitleAtIndex:buttonIndex] isEqualToString:@"Si"]){
        [self performSegueWithIdentifier:@"ToQuestion" sender:self];
    }
}

@end
